<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/19
 * Time: 16:51

 * 订单类
 */

namespace app\console\controller;
use think\Build;
use think\Db;
use think\Request;
use think\Url;
use app\interfaces\controller\Alipay;
use think\Exception;
use think\Session;
use think\Loader;
class ServiceOrder
{
    /**
     * @return array|mixed|\think\response\View
     * 订单列表
     */
    public function index()
    {
        $param = Request::instance()->param();
        $auding_status = Session::get('auding_status');
        if($auding_status == 1){
            $where['shop_id'] = ['eq',Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id')];
        }
        $where['o.order_type'] = ['eq', 2];
        $where['o.status'] = ['in','50,1,6,5,4,10,11,12,20'];
        if (!empty($param['status'])) $where['o.status'] = ['eq', $param['status']];
        if (!empty($param['shop_id'])) $where['shop_id'] = ['eq', $param['shop_id']];
        if (!empty($param['single_parent_id'])) $where['single_parent_id'] = ['eq', $param['single_parent_id']];
        if (!empty($param['title'])) $where['m.username|o.shop_order_number|o.order_number'] = ['eq', $param['title']];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['o.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        $data = \app\console\model\Order::alias('o')
            ->join('member m', 'o.member_id = m.id')
            ->join('single se','o.single_parent_id = se.id','left')
            ->join('shop s', 'o.shop_id = s.id','left')
            ->field('o.*,m.username,s.shop_title,se.cat_name')
            ->order('id','desc')
            ->where($where)
            ->paginate(10, false, $param)->each(function($item,$key){
                $item->cat_one = Db::name('single')->where('id',$item['single_id'])->value('cat_name');
                if($item['status'] == 12 || $item['status'] == 10 || $item['status'] == 11){
                   $item->refund_create_time = Db::name('order_refund')->where('order_id',$item['id'])->value('create_time');

                }
            });

        $total_count = Db::name('order o')
            ->join('member m', 'o.member_id = m.id')
            ->join('single se','o.single_parent_id = se.id','left')
            ->join('shop s', 'o.shop_id = s.id','left')
            ->field('o.*,m.username,s.shop_title,se.cat_name')
            ->where($where)->count();
        $total_price = Db::name('order o')
            ->join('member m', 'o.member_id = m.id')
            ->join('single se','o.single_parent_id = se.id','left')
            ->join('shop s', 'o.shop_id = s.id','left')
            ->field('o.*,m.username,s.shop_title,se.cat_name')
            ->where($where)->sum('amount');
        $shop_list = Db::name('shop s')->field('id,shop_title')->select();
        return view('', ['data' => $data,
            'shop_list' => $shop_list,
            'total_count' => $total_count,
            'total_price' => $total_price,
        ]);
    }

    /**
     * @param $id
     * 订单修改
     */
    public function update()
    {

            $number = db('config')->where('varname', 'web_number')->value('varvalue');
            $id = Request::instance()->param('id', '');
            $where_id = [];
            if ($id) {
                $where_id['o.id'] = ['eq', $id];
                $auding_status = Session::get('auding_status');
                if ($auding_status == 2) {
                    Db::name('order o')->where($where_id)->setField('is_read', 1);
                } else {
                    Db::name('order o')->where($where_id)->setField('is_read_shop', 1);
                }
            }
            $where_code = [];

            $param = Request::instance()->param();

            if (isset($param['code'])) {
                $date = date('Y-m-d H:i:s', time() - 300);
                $where_code['o.code'] = ['eq', 2];
                $where_code['o.status'] = ['eq', 6];
                $where_code['o.code_time'] = ['egt', $date];
            }
            $service_order = Db::name('order o')->where($where_id)->where($where_code)->find();
            $refund = Db::name('order_refund ors')->field('ors.*,rr.title')->where('order_id', $service_order['id'])->join('refund_reason rr', 'ors.reason_id = rr.id')->find();
            if (Request::instance()->isPost()) {

                if ($service_order['status'] == 50) { //当前数据库是1准备派单派单 //确认金额

                    if ($service_order['single_id'] != 11) { //非轮胎寄存
                        if ($param['amount'] <= 0) {
                            fail('请填写正确派单金额');
                        }
                        if ($param['shop_id'] <= 0) {
                            fail('请填写派单门店');
                        }
                        if ($param['freight'] > 0) { //商家配送
                            $ret = Db::name('order')->alias('o')
                                ->fetchSql(false)
                                ->where($where_id)
                                ->update([
                                    'shop_id' => $param['shop_id'],
                                    'amount' => $param['amount'] + $param['freight'],
                                    'order_price' => $param['amount'],
                                    'freight' => $param['freight'],
                                    'status' => 1, 'shipping' => 1,
                                    'shipping_province' => $param['shipping_province'],
                                    'shipping_address' => $param['shipping_address'],
                                    'shipping_phone' => $param['shipping_phone'],
                                    'shipping_name' => $param['shipping_name'],
                                ]);

                        } else { //门店自提
                            $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(
                                [   'shop_id' => $param['shop_id'],
                                    'amount' => $param['amount'],
                                    'order_price' => $param['amount'],
                                    'status' => 1, 'shipping' => 2,
                                    'shipping_province' => '',
                                    'shipping_address' => '',
                                    'shipping_phone' => '',
                                    'shipping_name' => ''
                                ]);
                        }
                        if ($ret) {
                            Db::name('member_message')->insert(
                                ['member_id' => $service_order['member_id'],
                                    'order_number' => $service_order['order_number'],
                                    'type_id' => 2,
                                    'title' => '您的订单金额及门店已确认,请支付',
                                    'content' => $service_order['order_number'],
                                    'is_click' => 1,
                                    'create_time' => date('Y-m-d H:i:s', time())
                                ]);

                            (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的订单金额及门店已确认,请支付', '订单金额:' . ($param['amount'] + $param['freight']) . '元,运费:' . $param['freight'] . '元', 2);
                            win('订单金额填写完毕', Url::build('index'));
                        }

                    } else {
                        //轮胎寄存

                        if ($param['shop_id'] <= 0) {
                            fail('请指派有效门店');
                        }

                        if ($param['amount'] > 0) {
                            $ret = Db::name('order o')->where('id', $id)->update(['shop_id' => $param['shop_id'], 'amount' => $param['amount'], 'order_price' => $param['amount'], 'status' => 1]);
                            if ($ret !== false) {
                                $hah = Db::name('member_message')->where('order_number', $service_order['order_number'])->update(
                                    [
                                        'title' => '您的服务订单(轮胎寄存)已指派门店,请到店扫码验证',
                                        'content' => $service_order['order_number'],
                                        'is_click' => 1,
                                        'create_time' => date('Y-m-d H:i:s', time())
                                    ]);

                                $shop_name = Db::name('shop')->where('id', $service_order['shop_id'])->value('shop_title');
                                (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单(轮胎寄存)已指派门店,请到店扫码验证', '寄存门店:' . $shop_name . ' 寄存金额为:' . $param['amount'] . '元', 2);
                                win('门店指派完毕(付费)', Url::build('index'));
                            }
                        } else {
                            $ret = Db::name('order o')->where('id', $id)->update(['shop_id' => $param['shop_id'], 'status' => 6]);//免费寄存
                            if ($ret !== false) {
                                $hah = Db::name('member_message')->where('order_number', $service_order['order_number'])->update(
                                    [
                                        'title' => '您的服务订单(轮胎寄存)已指派门店,请到店扫码验证',
                                        'content' => $service_order['order_number'],
                                        'is_click' => 1,
                                        'create_time' => date('Y-m-d H:i:s', time())
                                    ]);

                                $shop_name = Db::name('shop')->where('id', $service_order['shop_id'])->value('shop_title');
                                (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单(轮胎寄存)已指派门店,请到店扫码验证', '寄存门店:' . $shop_name . ' 免费寄存', 2);
                                win('门店指派完毕(免费)', Url::build('index'));
                            }
                        }


                    }

                }

                //            if($service_order['status'] == 1 && $service_order['shipping'] == 1 && isset($param['freight'])){ //配送方式2到点自取 1商家配送 last
                //                if($param['freight'] <= 0){
                //                    fail('请填写商家配送运费');
                //                }
                //                $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(['freight' => $param['freight'],'amount' => $service_order['amount'] + $param['freight'],'order_price' => $service_order['amount']+$param['freight']]);
                //                if ($ret !== false) {
                //                    Db::name('member_message')->where('order_number',$service_order['order_number'])->update(
                //                        [
                //                            'title' => '您的订单运费已确认,请支付',
                //                            'content' => $service_order['order_number'],
                //                            'is_click' => 1,
                //                            'create_time' => date('Y-m-d H:i:s',time())
                //                        ]);
                //
                //                    (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'],'您的订单运费已确认,请支付','运费为:'.$param['freight']);
                //                    win('运费确定完毕', Url::build('index'));
                //                }
                //
                //            }

//                if ($service_order['status'] == 6 && $service_order['code'] == 1) {
//                    if ($param['shop_id'] <= 0) {
//                        fail('请指派有效门店');
//                    }
//                    $ret = Db::name('order o')->where('id', $id)->update(['shop_id' => $param['shop_id']]);
//                    if ($ret !== false) {
//                        $hah = Db::name('member_message')->where('order_number', $service_order['order_number'])->update(
//                            [
//                                'title' => '您的服务订单已指派门店,请到店扫码验证',
//                                'content' => $service_order['order_number'],
//                                'is_click' => 1,
//                                'create_time' => date('Y-m-d H:i:s', time())
//                            ]);
//
//                        $shop_name = Db::name('shop')->where('id', $service_order['shop_id'])->value('shop_title');
//                        (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单已指派门店,请到店扫码验证', '门店为:' . $shop_name, 2);
//                        win('门店指派完毕', Url::build('index'));
//                    }
//
//                }


                $manage_id = Db::name('manager')->where('id', Session::get('manage_id'))->value('level');
                $auding_status = Db::name('auth_group')->where('id', $manage_id)->value('auding_status');//默认1没有审核权限

                if ($service_order['status'] == 6 && $service_order['code'] == 2 && $auding_status == 1 && $service_order['single_id'] != 11) {

                    $ret = Db::name('order o')->where($where_id)->where($where_code)->where('status', 6)->update(['status' => 5]);
                    if ($ret !== false) {
                        if (!empty($param['assignor_id'])) {
                            // 一对多添加数组
                            $shop_assignor_records = [];
                            for ($i = 0; $i < count($param['assignor_id']); $i++) {
                                $shop_assignor_records[$i]['order_id'] = $service_order['id'];
                                $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];
                                $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];
                                $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s',time());
                                $shop_assignor_records[$i]['shop_id'] = $service_order['shop_id'];
                                $shop_assignor_records[$i]['order_type'] = $service_order['order_type'];
                            }
                            Db::name('shop_assignor_records')->insertAll($shop_assignor_records);
                        }else{
                            fail('请分配人员');
                        }
                        win('人员分配完毕.', Url::build('index', ['code' => 1]));
                    }
                }
                if ($service_order['status'] == 6 && $service_order['code'] == 2 && $auding_status == 1 && $service_order['single_id'] == 11) {

                    $t = explode('/', Request::instance()->param('interval_timer'));
                    $multi_pic = serialize(Request::instance()->param('picArr/a'));
                    $remark = Request::instance()->param('remark');

                    $ret = Db::name('order o')->where($where_id)->where($where_code)->where('status', 6)->update(
                        [
                            'status' => 5,
                            'start_time' => $t[0],
                            'end_time' => $t[1],
                            'multi_pic' => $multi_pic,
                            'remark' => $remark
                        ]);
                    if ($ret !== false) {
                        if(empty($param['assignor_id'])){
                            fail('请添加门店人员');
                        }
                        if (!empty($param['assignor_id'])) {
                            // 一对多添加数组
                            $shop_assignor_records = [];
                            for ($i = 0; $i < count($param['assignor_id']); $i++) {
                                $shop_assignor_records[$i]['order_id'] = $service_order['id'];
                                $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];
                                $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];
                                $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());
                            }

                            Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                        }
                        win('人员分配完毕(轮胎寄存)', Url::build('index', ['code' => 1]));
                    }
                }

                if (isset($param['status']) && ($param['status'] == 11)) {
                    $find = Db::name('order')->find($id);
                    if ($find['pay_type'] == '2') {
                        $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '', $find['shop_order_number']);
                        if ($ret->code !== '10000') {
                            fail($ret->sub_msg);
                        }
                        //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);
                    } else if ($find['pay_type'] == '1') {
                        //halt('wx');
                        $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);
                        if ($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);
                    }
                    $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);
                    if ($ret !== false) {

                        (new Order())->refund($find['member_id'], $find['order_number']);
                        $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);
                        if ($refund_ret !== false) {
                            win('退货款处理完毕', Url::build('index'));
                        }
                    }
                }

                if (isset($param['status']) && ($param['status'] == 12)) {
                    $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);
                    if ($ret !== false) {
                        $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);
                        if ($refund_ret !== false) {
                            win('退货款失败处理完毕', Url::build('index'));
                        }
                    }
                }
            } //提交数据


            $order = \app\console\model\Order::alias('o')
                ->join('member m', 'o.member_id = m.id')
                ->join('single se', 'o.single_parent_id = se.id', 'left')
                ->join('shop s', 'o.shop_id = s.id', 'left')
                ->field('o.*,m.username,s.shop_title,se.cat_name')
                ->where($where_id)
                ->where($where_code)
                ->fetchSql(false)
                ->find();

            if ($order != null) {
                $order = $order->toArray();
                $order['one_cat'] = Db::name('single')->where('id', $order['single_id'])->value('cat_name');
            } else {
                fail('没有扫码订单');
            }
            if ($order['status'] == 10 || $order['status'] == 11 || $order['status'] == 12) {

                $order['refund_create_time'] = Db::name('order_refund')->where('order_id', $order['id'])->value('create_time');
            }
            if ($order['service_type_id'] == 1 || $order['service_type_id'] == 2 || $order['service_type_id'] == 3) { //1保险 2年检
                $order['service_info'] = Db::name('order_service')
                    ->where('order_id', $order['id'])
                    ->find();
                foreach (explode(',', $order['service_info']['type_id_str']) as $k => $v) {
                    $order['service_info']['type_id_name'][] = Db::name('protect_type')->where('id', $v)->value('title');
                }
            }

        $shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;
        $shop_assignor = Db::name('shop_assignor')->where('shop_id',$shop_id)->select();

            $shop_assignor_records = Db::name('shop_assignor_records sar')
                ->join('shop_assignor sa', 'sar.assignor_id = sa.id')
                ->where('order_id', $service_order['id'])
                ->field('sar.*,sa.name')
                ->select();


        return view('', ['item' => $order,'refund' => $refund,'shop_assignor' => $shop_assignor,'shop_assignor_records' => $shop_assignor_records]);
    }

    /**
     * @return array|mixed|\think\response\View
     * 卷码验证
     */
    public function code()
    {

        $auding_status = Session::get('auding_status');
        if($auding_status == 1){
            $where['o.shop_id'] = ['eq',Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id')];
        }
        $date = date('Y-m-d H:i:s',time()-300);
        $order = \app\console\model\Order::alias('o')
            ->join('member m', 'o.member_id = m.id')
            ->join('single se','o.single_parent_id = se.id','left')
            ->join('shop s', 'o.shop_id = s.id','left')
            ->field('o.*,m.username,s.shop_title,se.cat_name')
            ->where('o.code',2)
            ->whereTime('code_time','>=',$date)
            ->where('o.status',6)
            ->find();
        if($order != null) {
            $order = $order->toArray();
        }else{
            fail('没有扫码订单');
        }

        if(Request::instance()->isPost()){
            $param =  Request::instance()->param();
            if($order['status'] == 1) { //派单
                if($param['shop_id'] > 0 && $param['amount'] > 0){
                    $ret = Db::name('order')->where('id', $order['id'])->update(['amount' => $param['amount'], 'shop_id' => $param['shop_id'],'status' => 6]);
                    if ($ret) {
                        Db::name('member_message')->insert(
                            ['member_id' => $order['member_id'],
                                'order_number' => $order['order_number'],
                                'type_id' => 2,
                                'title' => '您的服务订单已派单,请支付',
                                'content' => $order['order_number'],
                                'is_click' => 1,
                                'create_time' => date('Y-m-d H:i:s',time())
                            ]);

                        win('派单成功', Url::build('index'));
                    }
                }else {
                    fail('派单失败');
                }
            }
        }
        $now_time = time();
        $code_time = strtotime($order['code_time']);
        if($order['code'] == 2 && $now_time - $code_time > 180){ //小于3分钟
            fail('请扫码验证3');
        }
        if($order['status'] == 10 || $order['status'] == 11 || $order['status'] == 12){
            $order['refund_create_time'] = Db::name('order_refund')->where('order_id',$order['id'])->value('create_time');
        }
        if($order['service_type_id'] == 1 || $order['service_type_id'] == 2){ //1保险 2年检
            $order['service_info'] = Db::name('order_service')
                ->where('order_id',$order['id'])
                ->find();
            foreach (explode(',',$order['service_info']['type_id_str']) as $k => $v){
                $order['service_info']['type_id_name'][] = Db::name('protect_type')->where('id',$v)->value('title');
            }
        }
        return view('', ['item' => $order]);

    }


    public function shop_assignor_records($id){
        $shop_assignor_records = Db::name('shop_assignor_records')->find($id);
        if(empty($shop_assignor_records)) return ['code' => 400,'message' => '此服务人员不存在'];
        $ret = Db::name('shop_assignor_records')->delete($id);
        if($ret){
            return ['code' => 200,'message' => '删除成功'];
        }
        return ['code' => 400,'message' => '失败'];
    }




}